import React, { useState, useEffect } from 'react';
import { 
  Button, 
  Tag, 
  Tooltip, 
  Space, 
  Card, 
  Descriptions, 
  Modal, 
  message, 
  Input, 
  Select, 
  Row, 
  Col,
  List,
  Avatar,
  Spin
} from 'antd';
import { 
  UserOutlined, 
  ReloadOutlined, 
  FilterOutlined,
  SearchOutlined,
  SortAscendingOutlined,
  TeamOutlined
} from '@ant-design/icons';
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';
import type { UserList, ListSerializerSuccessResponseUsers } from '@/services/generated/src/index';

const { Search } = Input;
const { Option } = Select;

interface EnhancedUsersListProps {
  groupId: number;
  groupName: string;
  visible: boolean;
  onClose: () => void;
}

const EnhancedUsersList: React.FC<EnhancedUsersListProps> = ({
  groupId,
  groupName,
  visible,
  onClose,
}) => {
  const [users, setUsers] = useState<UserList[]>([]);
  const [filteredUsers, setFilteredUsers] = useState<UserList[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedUser, setSelectedUser] = useState<UserList | null>(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);

  // 搜索和过滤状态
  const [searchText, setSearchText] = useState('');
  const [activeFilter, setActiveFilter] = useState<boolean | undefined>(undefined);
  const [staffFilter, setStaffFilter] = useState<boolean | undefined>(undefined);
  const [sortField, setSortField] = useState<string>('username');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('asc');

  // 加载用户列表
  const loadUsers = async () => {
    setLoading(true);
    try {
      await autoLoginInDev();

      // 🔑 关键：使用非分页Action，支持搜索、过滤、排序
      const requestParams: any = {
        id: groupId,
      };

      // 搜索功能 - 后端支持 username, email, first_name, last_name
      if (searchText.trim()) {
        requestParams.search = searchText.trim();
      }

      // 过滤功能 - 后端支持 is_active, is_staff
      if (activeFilter !== undefined) {
        requestParams.isActive = activeFilter;
      }
      if (staffFilter !== undefined) {
        requestParams.isStaff = staffFilter;
      }

      // 排序功能 - 后端支持 username, email, date_joined, last_login
      if (sortField) {
        requestParams.ordering = sortOrder === 'desc' ? `-${sortField}` : sortField;
      }

      console.log('🚀 非分页Action请求参数:', requestParams);

      const response = await apiClients.permissions.permissionsGroupsUsersRetrieve(requestParams);

      console.log('🎯 非分页Action响应:', response);

      // 🔑 关键：处理非分页响应 - 直接获取data数组
      const responseData = (response as any).data || response;
      const usersList = Array.isArray(responseData) ? responseData : [];
      
      setUsers(usersList);
      setFilteredUsers(usersList);
      
    } catch (error) {
      console.error('获取组用户列表失败:', error);
      message.error('获取组用户列表失败');
      setUsers([]);
      setFilteredUsers([]);
    } finally {
      setLoading(false);
    }
  };

  // 初始加载和参数变化时重新加载
  useEffect(() => {
    if (visible) {
      loadUsers();
    }
  }, [visible, searchText, activeFilter, staffFilter, sortField, sortOrder]);

  // 查看用户详情
  const handleViewDetail = (user: UserList) => {
    setSelectedUser(user);
    setDetailModalVisible(true);
  };

  // 重置筛选条件
  const handleReset = () => {
    setSearchText('');
    setActiveFilter(undefined);
    setStaffFilter(undefined);
    setSortField('username');
    setSortOrder('asc');
  };

  return (
    <>
      <Modal
        title={
          <Space>
            <TeamOutlined />
            <span>组用户列表 - {groupName}</span>
            <Tag color="green">非分页Action</Tag>
          </Space>
        }
        open={visible}
        onCancel={onClose}
        footer={[
          <Button key="close" onClick={onClose}>
            关闭
          </Button>
        ]}
        width={1000}
        style={{ top: 20 }}
      >
        <Card size="small" style={{ marginBottom: 16 }}>
          <Descriptions size="small" column={3}>
            <Descriptions.Item label="功能特性">
              <Space>
                <Tag icon={<SearchOutlined />} color="processing">实时搜索</Tag>
                <Tag icon={<FilterOutlined />} color="success">状态过滤</Tag>
                <Tag icon={<SortAscendingOutlined />} color="warning">排序</Tag>
              </Space>
            </Descriptions.Item>
            <Descriptions.Item label="数据模式">
              <Tag color="green">完整列表 (非分页)</Tag>
            </Descriptions.Item>
            <Descriptions.Item label="用户总数">
              <Tag color="blue">{users.length}</Tag>
            </Descriptions.Item>
          </Descriptions>
        </Card>

        {/* 搜索和过滤控件 */}
        <Card size="small" style={{ marginBottom: 16 }}>
          <Row gutter={16}>
            <Col span={8}>
              <Search
                placeholder="搜索用户名、邮箱、姓名"
                value={searchText}
                onChange={(e) => setSearchText(e.target.value)}
                allowClear
                enterButton={<SearchOutlined />}
              />
            </Col>
            <Col span={4}>
              <Select
                placeholder="激活状态"
                value={activeFilter}
                onChange={setActiveFilter}
                allowClear
                style={{ width: '100%' }}
              >
                <Option value={true}>激活</Option>
                <Option value={false}>未激活</Option>
              </Select>
            </Col>
            <Col span={4}>
              <Select
                placeholder="员工状态"
                value={staffFilter}
                onChange={setStaffFilter}
                allowClear
                style={{ width: '100%' }}
              >
                <Option value={true}>员工</Option>
                <Option value={false}>非员工</Option>
              </Select>
            </Col>
            <Col span={4}>
              <Select
                value={sortField}
                onChange={setSortField}
                style={{ width: '100%' }}
              >
                <Option value="username">用户名</Option>
                <Option value="email">邮箱</Option>
                <Option value="date_joined">加入时间</Option>
                <Option value="last_login">最后登录</Option>
              </Select>
            </Col>
            <Col span={2}>
              <Select
                value={sortOrder}
                onChange={setSortOrder}
                style={{ width: '100%' }}
              >
                <Option value="asc">升序</Option>
                <Option value="desc">降序</Option>
              </Select>
            </Col>
            <Col span={2}>
              <Space>
                <Button icon={<ReloadOutlined />} onClick={loadUsers} />
                <Button onClick={handleReset}>重置</Button>
              </Space>
            </Col>
          </Row>
        </Card>

        {/* 用户列表 */}
        <Spin spinning={loading}>
          <List
            dataSource={filteredUsers}
            renderItem={(user) => (
              <List.Item
                actions={[
                  <Button
                    key="detail"
                    type="link"
                    icon={<UserOutlined />}
                    onClick={() => handleViewDetail(user)}
                  >
                    详情
                  </Button>
                ]}
              >
                <List.Item.Meta
                  avatar={
                    <Avatar 
                      icon={<UserOutlined />} 
                      style={{ 
                        backgroundColor: user.is_active ? '#52c41a' : '#ff4d4f' 
                      }} 
                    />
                  }
                  title={
                    <Space>
                      <span>{user.username}</span>
                      {user.is_superuser && <Tag color="purple">超级用户</Tag>}
                      {user.is_staff && <Tag color="blue">员工</Tag>}
                      <Tag color={user.is_active ? 'green' : 'red'}>
                        {user.is_active ? '激活' : '禁用'}
                      </Tag>
                    </Space>
                  }
                  description={
                    <div>
                      <div>姓名: {user.first_name} {user.last_name}</div>
                      <div>邮箱: {user.email}</div>
                      <div>加入时间: {user.date_joined ? new Date(user.date_joined).toLocaleString() : '未知'}</div>
                      {user.last_login && (
                        <div>最后登录: {new Date(user.last_login).toLocaleString()}</div>
                      )}
                    </div>
                  }
                />
              </List.Item>
            )}
            locale={{
              emptyText: loading ? '加载中...' : '暂无用户数据'
            }}
            style={{ maxHeight: 400, overflowY: 'auto' }}
          />
        </Spin>

        {/* 统计信息 */}
        <Card size="small" style={{ marginTop: 16 }}>
          <Row gutter={16}>
            <Col span={6}>
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: 24, fontWeight: 'bold', color: '#1890ff' }}>
                  {filteredUsers.length}
                </div>
                <div>显示用户</div>
              </div>
            </Col>
            <Col span={6}>
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: 24, fontWeight: 'bold', color: '#52c41a' }}>
                  {filteredUsers.filter(u => u.is_active).length}
                </div>
                <div>激活用户</div>
              </div>
            </Col>
            <Col span={6}>
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: 24, fontWeight: 'bold', color: '#722ed1' }}>
                  {filteredUsers.filter(u => u.is_staff).length}
                </div>
                <div>员工用户</div>
              </div>
            </Col>
            <Col span={6}>
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontSize: 24, fontWeight: 'bold', color: '#fa8c16' }}>
                  {filteredUsers.filter(u => u.is_superuser).length}
                </div>
                <div>超级用户</div>
              </div>
            </Col>
          </Row>
        </Card>
      </Modal>

      {/* 用户详情Modal */}
      <Modal
        title={`用户详情 - ${selectedUser?.username}`}
        open={detailModalVisible}
        onCancel={() => {
          setDetailModalVisible(false);
          setSelectedUser(null);
        }}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={600}
      >
        {selectedUser && (
          <Descriptions column={1} bordered>
            <Descriptions.Item label="用户ID">
              {selectedUser.id}
            </Descriptions.Item>
            <Descriptions.Item label="用户名">
              {selectedUser.username}
            </Descriptions.Item>
            <Descriptions.Item label="姓名">
              {selectedUser.first_name} {selectedUser.last_name}
            </Descriptions.Item>
            <Descriptions.Item label="邮箱">
              {selectedUser.email}
            </Descriptions.Item>
            <Descriptions.Item label="状态">
              <Space>
                <Tag color={selectedUser.is_active ? 'green' : 'red'}>
                  {selectedUser.is_active ? '激活' : '禁用'}
                </Tag>
                {selectedUser.is_staff && <Tag color="blue">员工</Tag>}
                {selectedUser.is_superuser && <Tag color="purple">超级用户</Tag>}
              </Space>
            </Descriptions.Item>
            <Descriptions.Item label="加入时间">
              {selectedUser.date_joined ? new Date(selectedUser.date_joined).toLocaleString() : '未知'}
            </Descriptions.Item>
            <Descriptions.Item label="最后登录">
              {selectedUser.last_login ? new Date(selectedUser.last_login).toLocaleString() : '从未登录'}
            </Descriptions.Item>
          </Descriptions>
        )}
      </Modal>
    </>
  );
};

export default EnhancedUsersList;
